// 管理用户数据相关
import { defineStore } from "pinia";
import { ref } from "vue";
import { loginAPI } from "@/apis/user";
import { useCartStore } from "./cartStore";

export const useUserStore = defineStore(
  "user",
  () => {
    // const cartStore = useCartStore();
    // 1.定义管理用户数据的state
    const userInfo = ref({});
    // 2.定义管理接口数据的action函数
     const getUserInfo = async ({ username, password }) => {
      try {
        const res = await loginAPI({ username, password });
        console.log('获取用户信息成功:', res);
        // 兼容后端返回结构 code/msg/data，统一成 success/message/data
        const normalized = {
          success: res?.code === 200 || res?.success === true,
          message: res?.msg || res?.message || '',
          data: res?.data || res?.data || null,
          raw: res
        };
        userInfo.value = normalized;
        console.log('设置userInfo为:', normalized);
        
        // 登录成功后，尝试合并购物车
        if (normalized.success) {
          const cartStore = useCartStore();
          await cartStore.mergeCart();
        }
      } catch (error) {
        console.error('API调用出错:', error);
        throw error;
      }
    };
    
    // 退出时清空用户信息
    const clearUserInfo = () => {
      userInfo.value = {};
      const cartStore = useCartStore();
      cartStore.clearCart();
      // 清除持久化的购物车数据
      localStorage.removeItem('cart');
    };
    // 以对象的格式把state和action return
    return {
      userInfo,
      getUserInfo,
      clearUserInfo
    };
  },
  {
    persist: true,
  }
);